package com.main.sales.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.main.sales.common.CustomException;
import com.main.sales.dto.SetmealDto;
import com.main.sales.mapper.SetmealMapper;
import com.main.sales.pojo.Setmeal;
import com.main.sales.pojo.SetmealDish;
import com.main.sales.service.SetmealDishService;
import com.main.sales.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐,同时报讯套餐和菜品关联关系
     *
     * @param setmealDto
     */
    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐基本信息 stmeal
        this.save(setmealDto);

        //保存套餐和菜品关联信息 stmeal_dish
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐,同时删除套餐和菜品关联关系
     *
     * @param ids
     */
    @Transactional
    @Override
    public void deleteWithDish(List<Long> ids) {
        //删除套餐 select *f from setmeal id in (1,2,3) and status=1
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(Setmeal::getId, ids);
        lqw.eq(Setmeal::getStatus, 1);
        long count = this.count(lqw);
        if (count > 0) {
            throw new CustomException("套餐正在售卖中不能删除");
        }
        //批量删除
        this.removeByIds(ids);

        //删除套餐和菜品关联关系 delete * from setmeal where setmeal_id in (1,2,3)
        LambdaQueryWrapper<SetmealDish> lqwDish = new LambdaQueryWrapper<>();
        lqwDish.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(lqwDish);
    }
}
